package struts.xml;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import struts.form.XmlBean;

public class Struts_xml {
	public Struts_xml(){
		
	}
	
	public static Map<String,XmlBean> getXml(String xmlPath) throws Exception{
		SAXBuilder sax = new SAXBuilder();
		Document document = sax.build(new File(xmlPath));
		Element element = document.getRootElement();
		Element formElement = element.getChild("formbeans");
		Element actionElement = element.getChild("action-mapping");
		
		List<Element> actionList = actionElement.getChildren();
		List<Element> formList = formElement.getChildren();
		Map<String,XmlBean> bean = new HashMap<String,XmlBean>();
		for(int i = 0; i < actionList.size(); i++){
			XmlBean xmlBean = new XmlBean();
			String name = actionList.get(i).getAttributeValue("name");
			xmlBean.setActionName(name);
			xmlBean.setBeanName(name);
			String type = actionList.get(i).getAttributeValue("type");
			xmlBean.setActionType(type);
			String path = actionList.get(i).getAttributeValue("path");
			xmlBean.setActionPath(path);
			
			List<Element> forwardList = actionList.get(i).getChildren();
			Map<String,String> forwardMap = new HashMap<String,String>();
			for (Element element2 : forwardList) {
				String forwardName = element2.getAttributeValue("name");
				String forwardValue = element2.getAttributeValue("value");
				forwardMap.put(forwardName, forwardValue);
			}
			xmlBean.setForwardMap(forwardMap);
			
			for(int y = 0; y < formList.size(); y++){
				Element formEle = formList.get(y);
				if(name.equals(formEle.getAttributeValue("name"))){
					String className = formEle.getAttributeValue("class");
					xmlBean.setClassName(className);
					break;
				}
			}
			bean.put(path, xmlBean);
		}
		return bean;
	}
}
